package edu.gmu.client;

import edu.gmu.messages.EchoResponse;
import edu.gmu.messages.EchoRequest;
import edu.gmu.middleware.ClientDispatcher;
import edu.gmu.middleware.MessageEvent;
import edu.gmu.middleware.MessageListener;
import edu.gmu.middleware.Sink;
import edu.gmu.middleware.SinkFactory;
import java.io.IOException;

public class PublishClient
{
 
    public static void main( String[] args ) throws IOException, InterruptedException
    {
        String remoteAddress = "localhost";
        int remotePort       = Integer.parseInt(args[0]);
        
        Sink sink = SinkFactory.makeTCPSink( remoteAddress, remotePort );
        ClientDispatcher dispatcher = new ClientDispatcher(sink, 8, "PublishClient");
        
        
        dispatcher.addMessageListener( new MessageListener() 
        {
            public void messageReceived(MessageEvent event)
            {
                EchoResponse m = (EchoResponse)event.getMessage();
                System.out.println( "count="+m.count+" missive="+m.missive );
            }
        });
        dispatcher.start();
        sink.connect();
        
        dispatcher.subscribe(101, EchoResponse.class);
        
        int[] payload = new int[250000];
        for(int i = 0; i < payload.length; i++)
        {
            payload[i] = i;
        }
        
        
        EchoRequest request = new EchoRequest();
        request.missive = " from admirere :)";
        request.payload = payload;
        
        
        long start = 0;
        long stop  = 0;
        int delay  = 1;
        int iterations = (1000/delay)*1;
        long totalTime = 0;
        for( int i = 0; i < iterations; i++ )
        {
            request.count = i;
            
            start = System.currentTimeMillis();
            dispatcher.publish(100,request);
            stop  = System.currentTimeMillis();
            long diff = (stop-start);
            totalTime+=diff;
            System.out.println( "Diff="+diff );
            Thread.sleep(delay);
        }
        System.out.println( "Avg Diff="+ (totalTime/iterations) );
        dispatcher.stop();
    }
}